package com.h117121.fashionshop.core.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.h117121.fashionshop.core.dao.generic.GenericDaoImpl;
import com.h117121.fashionshop.core.dom.Account;
import com.h117121.fashionshop.core.dom.ResultPage;
import com.h117121.fashionshop.core.exception.AccountNotFoundException;

@Repository("accountDao")
public class AccountDaoImpl extends GenericDaoImpl<Account, Long> implements
		AccountDao {

	@SuppressWarnings("unchecked")
	@Override
	public Account findByUsername(String username)
			throws AccountNotFoundException {
		List<Account> rs = getSessionFactory().getCurrentSession()
				.createQuery("from Account where username='" + username + "'")
				.list();
		if (rs.size() == 0) {
			throw new AccountNotFoundException();
		} else {
			return rs.get(0);
		}
	}

	@Override
	public ResultPage getByKeyword(String keyword, int index, int numItems) {
		long id = -1;
		try {
			id = Long.parseLong(keyword);
		} catch (NumberFormatException ex) {
		}

		Query query = getSessionFactory().getCurrentSession().createQuery(
				"from " + getEntityClass().getSimpleName()
						+ " where lower(userName) like "
						+ formatLikeString(keyword) + " OR lower(name) like "
						+ formatLikeString(keyword)
						+ ((id != -1) ? (" OR id = " + id) : ""));
		query.setMaxResults(numItems);
		query.setFirstResult(index * numItems);

		long totalNumItems = (((Long) getSessionFactory()
				.getCurrentSession()
				.createQuery(
						"select count(*) from "
								+ getEntityClass().getSimpleName()
								+ " where lower(userName) like "
								+ formatLikeString(keyword)
								+ " OR lower(name) like "
								+ formatLikeString(keyword)
								+ ((id != -1) ? (" OR id = " + id) : ""))
				.iterate().next()).longValue());
		long numPage = (totalNumItems % numItems == 0) ? (totalNumItems / numItems)
				: (1 + totalNumItems / numItems);

		ResultPage result = new ResultPage();
		result.setNumPage(numPage);
		result.setCurrentPage(index);
		result.setNumItems(totalNumItems);
		result.setResult(query.list());

		return result;
	}
}
